// File: src/public/engine/metal/customerTransitionMgr.js

import { MetalCombineOrder, MetalCombineOrderFilter } from "./metalCombineOrder";
import { CommodityUiAction } from '../uiAction/commodityUiAction'
import { SubCommodityFilter, SubCommodityMetalFilterTypeEnum } from '../commodity/subCommodity'
import { DataPage } from '../../network/communicationConverter'
import { MetalUiAction } from "../uiAction/metalUiAction";
import { Engine } from "../engine";
import { Util } from "../../utils/util";
import {CombineOrderType} from '../common/docDefinition.js';

// 商品出入库类型
export const TransactionCellType = {
    Date: 1,    // 日期
    Title: 2,   // 摘要

    SalesCommodityCount: 3,     // 销售数量
    SaleCommodityPrice: 4,    // 销售单价
    SalesCommodityBatchPrice: 5,  // 销售总价 应收款
    PurchaseCommodityCount: 6,  // 采购数量
    PurchaseCommodityPrice: 7,  //  采购单价
    PurchaseCommodityBatchPrice: 8,  //  采购总价 应付款

    MetalIn: 9,  // 贵金属存入
    MetalOut: 10, // 贵金属取出后

    Receipt: 11, // 收款
    Payment: 12, // 付款

    SwapFee: 13, // 仓息

    MetalBanlance: 14, // 贵金属结余
    Balance: 15,  // 存欠款后

    Remark: 16, // 备注    
};

export class CustomerTransictionMgr {
    _orders = [];  // MetalCombineOrder
    _removedOrders = [];
    metalCommodities = [];  // 商户支持的贵金属商品 (贵金属本身) SubCommodity
    _commodityUiAction = null;
    _metalUiAction = null;
    _filter = new MetalCombineOrderFilter();
    emptyLine = 1;

    _errorStatus = false;

    _isEdited = false;

    _targetObj = null;

    get isEdited() {
        return this._isEdited;
    }


    constructor({ commodityUiAction, metalUiAction, targetObj } = {}) {
        this._commodityUiAction = commodityUiAction || new CommodityUiAction();
        this._metalUiAction = metalUiAction || new MetalUiAction();
        this._targetObj = targetObj;
    }

    async initData() {
        await Promise.all([
            this.getMetalCommodityInfo(),
            this.getList(),
        ]);

        return !this._errorStatus;
    }


    // 客户综合单据列表刷新
    async refreshCustomerData(pageNum = 1, pageSize = 1000, dateRange = null) {
        const result = await this.getList(
            pageNum,
            pageSize,
            dateRange
        );

        if(result.dataList){
            this._removedOrders = [];
            this._isEdited = false;
            this.fillEmptyLine();
            this.updateTransData();
        }

        return result;

    }

    fillEmptyLine() {
        console.log('customerTransitionMgr fillEmptyLine. targetObj: metalCommodities:', this._targetObj, this.metalCommodities);
        // 如果没有期初记录，插入一条期初记录        

        if (this._orders.length == 0 || !this._orders[0].isPeriodInitial) {
            let periodInitOrder = MetalCombineOrder.emptyWithNull({
                metalCommodities: this.metalCommodities,                
                combineOrderType:CombineOrderType.PeriodInitalRnd,
                targetObject: this._targetObj,
            });
            periodInitOrder.title = "期初记录";
            this._orders.unshift(periodInitOrder);

        }

        // 插入空行，方便数据插入
        for (let i = 0; i < this.emptyLine; i++) {
            this._orders.push(MetalCombineOrder.emptyWithNull({ metalCommodities: this.metalCommodities, targetObject: this._targetObj, }));
        }

        /*
        // 结尾测试记录
         let tailTestOrder = MetalCombineOrder.empty({ 
                metalCommodities: this.metalCommodities,              
            });
        tailTestOrder.title = "测试记录";
        this._orders.push(tailTestOrder);
        */
    }

    // 获取贵金属商品信息
    async getMetalCommodityInfo() {
        const res = await this._commodityUiAction.getCommoditySpecList(
            new DataPage(1, 0, 100),  // 大一些保障所有贵金属拿到     
            (new SubCommodityFilter({ metalType: SubCommodityMetalFilterTypeEnum.MetalSelfOnly })).toJson()
        )

        if (res?.data?.dataList) {
            this.metalCommodities = res.data.dataList;
            return null;
        }

        this._errorStatus = true;
        return "get metal commodity info failed"
    }

    async getList(pageNum = 1, pageSize = 1000, dateRange = null) {
        let ret = null;
        try {
            // Update filter with date range
            if (dateRange?.length === 2) {
                this._filter.startDate = dateRange[0];
                this._filter.endDate = new Date(dateRange[1])
                this._filter.endDate.setHours(23, 59, 59, 999)
            } else {
                this._filter.startDate = null
                this._filter.endDate = null
            }

            // 过滤指定用户数据
            this._filter.targetObjId = this._targetObj?.id

            const res = await this._metalUiAction.getMetalCombineData({
                pageInfo: new DataPage(pageNum, 0, pageSize),
                filter: this._filter.toJson({ withState: true })
            })

            if (res?.data?.dataList) {
                this._orders = res.data.dataList
                ret = {
                    dataList: res.data.dataList,
                    total: res.data.pageInfo?.total || res.data.dataList.length
                };
            } else if (res?.resErr) {
                this._errorStatus = true;
                console.error('获取综合单据列表失败: ' + res.resErr)
            }

            ret = ret || "get metal combine order list failed"
        } catch (error) {
            this._errorStatus = true;
            console.error('获取综合单据列表失败', error)
            ret = "get metal combine order list failed"
        } finally {
            return ret;
        }
    }

    addOrder(order) {
        this._orders.push(order);
        this.calculateTotalData();
    }

    removeOrder(order) {
        let removedOrder = this._orders.splice(this._orders.indexOf(order), 1);

        if (removedOrder && Util.isEmpty(removedOrder.id)) {
            this._removedOrders.push(removedOrder[0]);
        }
        this.updateTransData();
    }

    get orders() {
        return this._orders;
    }

    // 计算累计数据
    calculateTotalData() {
        // 第一条为期初记录
        if (this._orders.length <= 1) {
            return;
        }

        let lastOrder = this._orders[0];

        for (let i = 0; i < this._orders.length; i++) {
            // 存欠款

            

            this._orders[i].setBalanceBefore(lastOrder.balanceAfter);

            // 遍历所有贵金属存欠料（贵金属类型，单据初始化的时候把没有的贵金属全部都按0值补齐了的
            // 所以下列的getAccount 都应该是能够找得到数据）
            let customerFundAccountTypeList = Engine.profile.org.customerFundAccountTypeList;
            for (let j = 0; j < customerFundAccountTypeList.length; j++) {
                let accountType = customerFundAccountTypeList[j];              

                let metalBalance = this._orders[i].getMetalBalanceByMetalFoundTypeId(accountType.id);
                let metalBalanceLastOrder = lastOrder.getMetalBalanceByMetalFoundTypeId(accountType.id)
                metalBalance.setBalanceBefore(metalBalanceLastOrder.balanceAfter,this._orders[i]);
            }

            lastOrder = this._orders[i];
        }
    }

    // 更新订单信息
    updateTransData() {
        console.log("customerTransitionMgr updateTransData.")
       
        this._isEdited = false;
        if (this._removedOrders.length > 0) {
            this._isEdited = true;
        } else {
            this._orders.forEach(order => {
                if (order.isEdited) {
                    this._isEdited = true;
                }
            })
        }


        // 判断如果最后一条记录为空，自动增加空行
        if (!this._orders[this._orders.length - 1].isEmptyOrder()) {
            for (let i = 0; i < this.emptyLine; i++) {
                this._orders.push(MetalCombineOrder.emptyWithNull({
                    metalCommodities: this.metalCommodities,
                    targetObject: this._targetObj,
                }));
            }
        }

         this.calculateTotalData();
    }



    // 检查数据完成性
    checkDataComplete() {
        if (!this._isEdited) {
            return { errorMsg: "无记录更新！" };
        }


        for (let i = 0; i < this._orders.length; i++) {
            let order = this._orders[i];
            if (order.isEdited) {
                let ret = order.validateOrder();

                if (ret) {
                    ret.errorMsg = "第" + (i + 1) + "行数据不完整: " + ret.errorMsg
                    ret.msgBoxConfirm = true;
                    return ret;
                }
            }
        }

        return null;
    }


    // 更新订单json      
    toJson_TransBatch() {
        let batchJson = [];
        let delOrders = [];
        let orgId = Engine.profile.org.orgId;

        for (let i = 0; i < this._orders.length; i++) {

            let order = this._orders[i];
            // 设置当前index , 方便数据库同步数据
            order.indexInTransaction = i;
            if (order.isEdited) {
                let json = order.toJson();
                json.orgId = orgId;
                batchJson.push(json);
            }
        }

        if (this._removedOrders.length > 0) {
            for (let i = 0; i < this._removedOrders.length; i++) {

                delOrders.push(this._removedOrders[i].id);
            }
        }

        return {
            orders: batchJson,
            delOrders: delOrders
        }
    }


}